<template>
  <!-- 最外层的容器 -->
  <view class="my-checkout-container">
    <!-- 全选区域 -->
    <label class="radio" @click="checkAllHandler">
      <radio color="#C00000" :checked="isCheckedAll" />
      <text>全选</text>
    </label>

    <!-- 合计区域 -->
    <view class="amount-box">
      合计:<text class="amount">￥{{ checkedAmount | formatNum }}</text>
    </view>

    <!-- 结算按钮 -->
    <view class="btn-checkout" @click="checkoutFn"
      >结算({{ checkedTotal }})</view
    >
  </view>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
export default {
  data() {
    return {
      // 倒计时的秒数
      seconds: 3,
      // 倒计时定时器
      timer: null
    }
  },
  computed: {
    ...mapGetters('cart', ['checkedTotal', 'total', 'checkedAmount']),
    ...mapGetters('user', ['fullAddress']),
    ...mapState('user', ['token']),
    ...mapState('cart', ['cartItems']),
    // 是否全选
    isCheckedAll() {
      return this.checkedTotal === this.total
    }
  },
  methods: {
    // 结算
    checkoutFn() {
      // 1. 判断是否勾选商品
      if (this.checkedTotal === 0) return this.$showMsg('请勾选商品')
      // 2. 判断是否选择收货地址
      if (!this.fullAddress) return this.$showMsg('请填写收货地址')
      // 3. 是否已登录
      if (!this.token) return this.delayNavigate()
      // 4. 微信支付
      this.payOrder()
    },
    // 结算订单
    async payOrder() {
      // 1. 创建订单
      const goods = this.cartItems
        .filter(item => item.goods_state)
        .map(({ goods_id, goods_count: goods_number, goods_price }) => ({
          goods_id,
          goods_number,
          goods_price
        }))
      // 1.1 发送请求
      const {
        meta: { status },
        message
      } = await this.$http.post('/my/orders/create', {
        order_price: 0.01,
        consignee_addr: this.fullAddress,
        goods
      })
      if (status !== 200) return this.$showMsg()

      // 1.2 得到 “订单编号”
      const orderNumber = message.order_number
      // 2. 订单预支付
      // 2.1 请求获取订单的支付信息
      const { meta: meta2, message: message2 } = await this.$http.post(
        '/my/orders/req_unifiedorder',
        {
          order_number: orderNumber
        }
      )

      // 2.2 预付订单生成失败
      if (meta2.status !== 200) {
        return this.$showMsg('预付订单生成失败！')
      }

      // 2.3 得到订单支付相关的必要参数
      const payInfo = message2.pay

      // 3. 发起微信支付
      // 3.1 弹出微信支付界面
      const [err, res] = await uni.requestPayment(payInfo)

      if (err) {
        return this.$msg('订单支付失败！')
      }

      // 3.2 查询支付结果
      const { meta: meta3 } = await this.$http.post('/my/orders/chkOrder', {
        order_number: orderNumber
      })

      if (meta3.status !== 200) {
        return this.$msg('订单支付失败！')
      }

      // 3.3 提示支付完成
      this.$msg('订单支付成功')
    },
    // 未登录跳转事件
    delayNavigate() {
      // 1. 重置秒数
      this.seconds = 3

      // 2. 初次展示提示消息
      this.$showMsg('请登录后再结算！' + this.seconds + ' 秒后自动跳转到登录页')

      // 3. 创建定时器
      this.timer = setInterval(() => {
        // 3.1 递减秒数
        this.seconds--

        // 3.2 判断秒数 <= 0 则清除定时器并跳转
        if (this.seconds <= 0) {
          clearInterval(this.timer)
          this.$store.commit('user/setRedirectInfo', {
            type: 'tab',
            url: '/pages/cart/cart'
          })
          uni.switchTab({ url: '/pages/my/my' })
        } else {
          // 3.3 否则继续显示倒计时信息
          this.$showMsg(
            '请登录后再结算！' + this.seconds + ' 秒后自动跳转到登录页'
          )
        }
      }, 1000)
    },
    // 全选和取消全选事件
    checkAllHandler() {
      this.$store.commit('cart/updateAllState', !this.isCheckedAll)
    }
  }
}
</script>

<style lang="scss">
.my-checkout-container {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 100rpx;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10rpx;
  font-size: 28rpx;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-checkout {
    height: 100rpx;
    min-width: 200rpx;
    background-color: #c00000;
    color: white;
    line-height: 100rpx;
    text-align: center;
    padding: 0 20rpx;
  }
}
</style>
